package com.lt.springbootcrm.service.impl;

import com.lt.springbootcrm.entity.User;
import com.lt.springbootcrm.repository.UserRepository2;
import com.lt.springbootcrm.service.UserService;
import jakarta.annotation.Resource;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Service
public class UserServiceImpl implements UserService {

    @Resource
    UserRepository2 userRepository2;

    @Override
    public Page<User> findPageByMap(Map param, Pageable pageable) {
        return userRepository2.findAll(new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<Predicate>();
                if(param.get("usrName") != null){
                    predicates.add(criteriaBuilder.like(root.get("usrName"),"%"+param.get("usrName")+"%"));
                }
                if(param.get("roleId")!=null){
                    predicates.add(criteriaBuilder.equal(root.get("usrRoleId"),param.get("roleId")));
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }

        }
        ,pageable);
    }
}
